<template>
  <div class="chat-container">
    <div class="messages-list">
      <el-scrollbar
        style="height: 70vh; overflow-x: hidden"
        ref="scrollbarMsgList"
      >
        <MsgItem
          v-for="(item, index) in messageList"
          :key="index"
          :information="item"
        />
        <UpmsgItem
          v-for="(item, index) in messageListUping"
          :key="index"
          :avatar="avatar"
          :item="item"
        />
      </el-scrollbar>
    </div>
    <div v-if="group_id != '0'">
      <div class="fun-icon">
        <div class="fun-icon-item">
          <div
            class="el-upload el-upload--picture-card"
            @click.stop="emojiShow = true"
          >
            <el-icon class="single-upload__add-btn">
              <PictureRounded />
            </el-icon>
          </div>
        </div>
        <div class="fun-icon-item">
          <SingleImage
            v-model="imgUrl"
            @up-ing="sendMessageIng"
            @up-success="sendImgMessage"
          />
        </div>
        <div class="fun-icon-item">
          <el-button type="primary" size="small" @click="sendTextMessage">
            发送
          </el-button>
        </div>
      </div>

      <div>
        <Emoji v-if="emojiShow" @click-emoji="clickEmoji" />
        <el-input
          v-else
          type="textarea"
          :rows="6"
          @keyup="handleCtrlEnter"
          v-model="message"
          placeholder="请输入内容"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import MsgItem from "./components/msgitem.vue";
import Emoji from "./components/emoji.vue";
import SingleImage from "./components/singleImage.vue";
import UpmsgItem from "./components/upmsgItem.vue";
import { type ChatHistory, MessageItem } from "@/utils/socket";
// WebSocket 相关状态
const link = ref(import.meta.env.VITE_APP_WS_URL);
const socket = ref<WebSocket | null>(null);
const connectionStatus = ref("disconnected");
const token = ref("");
const scrollbarMsgList = ref();
const emojiShow = ref(false);
const imgUrl = ref("");
const messageList = ref<ChatHistory[]>([]);
const messageListUping = ref<MessageItem[]>([]);
const avatar = ref(
  "https://wgcys.oss-cn-shanghai.aliyuncs.com/uploads/20250417/b23860431b12a272c31918cd30e394a9.png"
);
const message = ref("");
const group_id = ref("0");
const admin_id = ref("0");
const heartbeatTimer = ref<number | null>(null);

const onLogin = () => {
  /**
   *ID string `json:"id"`
	//消息类型  login 登录, logout 退出, ping 心跳, text 文本消息,  image 图片消息, video 视频消息, audio 音频消息
	Type string `json:"type"`
	//用户类型  member 成员, admin 管理员
	UserType string `json:"user_type"`
	//客服id
	AdminID string `json:"admin_id"`
	//消息组ID
	GroupID string `json:"group_id"`
	//消息内容
	Content string `json:"content"`
   */
  let data = {
    type: "login",
    user_type: "member",
    admin_id: admin_id.value,
    content: token.value,
  };
  sendMessage(JSON.stringify(data));
};

const connectWebSocket = () => {
  if (socket.value) {
    socket.value.close();
  }
  socket.value = new WebSocket(link.value);

  socket.value.onopen = () => {
    connectionStatus.value = "connected";
    console.log("WebSocket 连接已建立");
    onLogin();
    HeartBeat();
  };

  socket.value.onmessage = (event) => {
    // messages.value.push(event.data);
    // message.value = event.data;
    const tempData = JSON.parse(event.data);
    console.log("收到消息:", tempData);
    switch (tempData.type) {
      case "login":
        group_id.value = tempData.group_id + "";
        GetMessageList(1);
        break;
      case "msg":
        const content = tempData.content;
        const contentData = JSON.parse(content);
        console.log("contentData", contentData);
        messageList.value = contentData.list.reverse();
        scrollToBottom();
        break;
      case "text":
      case "image":
      case "video":
      case "audio":
        messageList.value.push(tempData);
        scrollToBottom();
        break;
      default:
        break;
    }
  };

  socket.value.onclose = () => {
    connectionStatus.value = "disconnected";
    console.log("WebSocket 连接已关闭");
  };

  socket.value.onerror = (error) => {
    console.error("WebSocket 错误:", error);
  };
};
const HeartBeat = () => {
  if (heartbeatTimer.value) {
    clearInterval(heartbeatTimer.value);
  }

  heartbeatTimer.value = window.setInterval(() => {
    const data = {
      type: "ping",
      content: "ping",
    };
    socket.value?.send(JSON.stringify(data));
  }, 9000); // 假设心跳间隔为5000ms，根据实际需求调整
};

const GetMessageList = (page: number) => {
  if (socket.value && connectionStatus.value === "connected") {
    let data = {
      type: "msg",
      user_type: "member",
      page: page,
      content: "",
    };
    socket.value.send(JSON.stringify(data));
    // message.value = "";
  } else {
    alert("WebSocket 未连接");
  }
};
const clickEmoji = (item: any) => {
  console.log(item);
  emojiShow.value = false;
  message.value += item;
};
const sendMessage = (json: any) => {
  if (socket.value && connectionStatus.value === "connected") {
    socket.value.send(json);
    // message.value = "";
  } else {
    alert("WebSocket 未连接");
  }
};

const handleCtrlEnter = (e: any) => {
  console.log(e);
  if (e.ctrlKey && e.keyCode == 13) {
    console.log("ctrl+enter");
    message.value += "\r";
    return false;
  } else if (e.keyCode == 13) {
    // message.value = message.value.replace(/\r+$/, "");
    console.log("enter");
    sendTextMessage();
  }
};

const sendTextMessage = () => {
  let sendData = {
    type: "text",
    user_type: "member",
    group_id: group_id.value + "",
    user_id: admin_id.value + "",
    content: message.value,
  };
  if (socket.value && connectionStatus.value === "connected") {
    console.log("发送", JSON.stringify(sendData));
    socket.value.send(JSON.stringify(sendData));
    message.value = "";
  } else {
    alert("WebSocket 未连接");
  }
};

//  发送图片视频音频 发送中
const sendMessageIng = (item: any) => {
  // items.forEach((item: { name: string; uid: string; url: string }) => {
  //   const sendData: MessageItem = {
  //     type: "image",
  //     user_type: "admin",
  //     group_id: group_id.value + "",
  //     user_id: admin_id.value + "",
  //     content: item.url,
  //     uid: item.uid,
  //   };
  //   messageListUping.value.push(sendData);
  // });
  // scrollToBottom();
  const sendData: MessageItem = {
    type: item.type,
    user_type: "member",
    group_id: group_id.value + "",
    user_id: admin_id.value + "",
    content: item.url,
    uid: item.uid + "",
  };
  // console.log("sendMessageIng", JSON.stringify(sendData));
  messageListUping.value.push(sendData);
  scrollToBottom();
};
const sendImgMessage = (item: any) => {
  let sendData = {
    type: item.type,
    user_type: "member",
    group_id: group_id.value + "",
    user_id: admin_id.value + "",
    content: item.url,
  };
  if (socket.value && connectionStatus.value === "connected") {
    // console.log("发送", JSON.stringify(sendData));
    socket.value.send(JSON.stringify(sendData));
    messageListUping.value = messageListUping.value.filter(
      (itemx: any) => itemx.uid != item.uid
    );
    message.value = "";
    imgUrl.value = "";
  } else {
    alert("WebSocket 未连接");
  }
};

//滚动到底部
const scrollToBottom = () => {
  // console.log("滚动到底部", "");
  setTimeout(() => {
    nextTick(() => {
      const wrapElement = (
        scrollbarMsgList.value?.$el as HTMLElement
      )?.querySelector(".el-scrollbar__wrap") as HTMLElement | null;
      if (wrapElement) {
        wrapElement.scrollTop = wrapElement.scrollHeight;
      }
    });
  }, 500);
};
onMounted(() => {
  // 修改标题
  document.title = "聊天室";
  //获取url参数 admin_id 和 token
  const hashPart = window.location.hash.split("?")[1] || "";
  const query = new URLSearchParams(hashPart);
  console.log(query);
  admin_id.value = query.get("admin_id") || "";
  token.value = query.get("token") || "";
  if (admin_id.value && token.value) {
    connectWebSocket();
  }
});

onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close();
  }
});
</script>
<style>
html,
body,
#app {
  display: inline-block !important;
}
</style>
<style scoped>
.chat-container {
  background-color: #f5f8fd;
}
.messages {
  margin-top: 20px;
}

:deep(.el-upload--picture-card) {
  /*  width: var(--el-upload-picture-card-size);
  height: var(--el-upload-picture-card-size); */
  width: 50px;
  height: 50px;
}

.fun-icon {
  width: 100%;
  margin-bottom: 15px;
}

.fun-icon-item {
  margin-right: 10px;
  width: fit-content;
  display: inline-block;
}
</style>
